package com.water.camera.fragment

import android.content.Intent
import android.os.Bundle
import androidx.annotation.NonNull
import androidx.annotation.Nullable
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentTransaction

class ActivityResultFragment : Fragment() {
    private var onActivityResultListener: ActivityResultListener? = null
    override fun onCreate(@Nullable savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        onActivityResultListener!!.onRequest(this)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, @Nullable data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        onActivityResultListener!!.onActivityResult(requestCode, resultCode, data)
        if (activity != null) {
            val transaction: FragmentTransaction =
                requireActivity().supportFragmentManager.beginTransaction()
            transaction.remove(this)
            transaction.commit()
        }
    }

    interface ActivityResultListener {
        fun onRequest(fragment: ActivityResultFragment?)
        fun onActivityResult(requestCode: Int, resultCode: Int, @Nullable data: Intent?)
    }

    companion object {
        private const val TAG = "ActivityResultFragment"
        fun registerActivityResult(
            activity: FragmentActivity,
            @NonNull listener: ActivityResultListener
        ) {
            val transaction: FragmentTransaction =
                activity.supportFragmentManager.beginTransaction()
            var fragment =
                activity.supportFragmentManager.findFragmentByTag(TAG) as? ActivityResultFragment
            if (fragment == null) {
                fragment = ActivityResultFragment()
            }
            fragment.onActivityResultListener = listener
            if (fragment.isAdded) {
                listener.onRequest(fragment)
            } else {
                transaction.add(fragment, TAG)
            }
            transaction.commit()
        }
    }
}


interface FileUtilCallback {
    fun onResult(success: Boolean)
}
